package com.kpx.app.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kpx.app.R;
import com.kpx.app.base.ActivityBase;
import com.kpx.app.bean.CertificationInfoBean;
import com.kpx.app.bean.PhotoBgInfo;
import com.kpx.app.bean.UploadBean;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.ImageLoader;
import com.kpx.app.utils.ImageUtils;
import com.kpx.app.utils.ImagesBulkUpload;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.StringUtil;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.datautils.FileUtils;
import com.kpx.app.utils.encrypt.BitmapHelper;
import com.kpx.app.utils.uiutils.DisplayUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.TitleView;
import com.kpx.app.wigdet.BottomUpDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.PhotoPreviewActivity;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by congdy on 17/3/5.
 * 照片认证
 */
@RuntimePermissions
public class ActivityCertificationPhoto extends ActivityBase implements ImageUtils.SelectImageListener {
    @BindView(R.id.titleview)
    TitleView titleview;
    @BindView(R.id.img_photo1)
    ImageView imgPhoto1;
    @BindView(R.id.txt_photo1)
    TextView txtPhoto1;
    @BindView(R.id.img_photo2)
    ImageView imgPhoto2;
    @BindView(R.id.txt_photo2)
    TextView txtPhoto2;
    @BindView(R.id.img_photo3)
    ImageView imgPhoto3;
    @BindView(R.id.txt_photo3)
    TextView txtPhoto3;
    @BindView(R.id.img_photo4)
    ImageView imgPhoto4;
    @BindView(R.id.txt_photo4)
    TextView txtPhoto4;
    @BindView(R.id.img_photo5)
    ImageView imgPhoto5;
    @BindView(R.id.txt_photo5)
    TextView txtPhoto5;
    @BindView(R.id.btn_uplade)
    Button btnUplade;
    @BindView(R.id.txt_progress1)
    TextView txtProgress1;
    @BindView(R.id.txt_progress2)
    TextView txtProgress2;
    @BindView(R.id.txt_progress3)
    TextView txtProgress3;
    @BindView(R.id.txt_progress4)
    TextView txtProgress4;
    @BindView(R.id.txt_progress5)
    TextView txtProgress5;
    @BindView(R.id.txt_fail_msg)
    TextView txt_fail_msg;
    @BindView(R.id.rl_1)
    RelativeLayout rl1;
    @BindView(R.id.rl_2)
    RelativeLayout rl2;
    @BindView(R.id.rl_3)
    RelativeLayout rl3;
    @BindView(R.id.rl_4)
    RelativeLayout rl4;
    @BindView(R.id.rl_5)
    RelativeLayout rl5;
    private int toPhotoPositon = 0;
    private int toShowPositon = 0;
    /**
     * 从相册选择照片回调
     */
    public static final int REQUEST_CODE_CAPTURE = 6;
    private static final int REQUEST_CODE_CROP_ICON = 9;
    /**
     * 拍摄照片回调
     */
    public static final int REQUEST_CODE_CALLERY = 7;

    private ArrayList<UploadBean> cpBeans = new ArrayList<UploadBean>();
    private ArrayList<UploadBean> failuplist = new ArrayList<UploadBean>();
    private ArrayList<ImageView> imageViews = new ArrayList<ImageView>();
    private CertificationInfoBean b;

    @Override
    public void initview(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_certification_photo);
        ButterKnife.bind(this);
        UIUtils.setNormalTitle(titleview, "照片认证");
        imageViews.add(imgPhoto1);
        imageViews.add(imgPhoto2);
        imageViews.add(imgPhoto3);
        imageViews.add(imgPhoto4);
        imageViews.add(imgPhoto5);
        DisplayUtil.setViewWH_L_new(ActivityCertificationPhoto.this, rl1, (float) 108 / 130, 3, 90);
        DisplayUtil.setViewWH_L_new(ActivityCertificationPhoto.this, rl2, (float) 108 / 130, 3, 90);
        DisplayUtil.setViewWH_L_new(ActivityCertificationPhoto.this, rl3, (float) 108 / 130, 3, 90);
        DisplayUtil.setViewWH_L_new(ActivityCertificationPhoto.this, rl4, (float) 137 / 185, 2, 120);
        DisplayUtil.setViewWH_L_new(ActivityCertificationPhoto.this, rl5, (float) 137 / 185, 2, 120);

    }

    @Override
    public void initData() {
        for (int i = 0; i < 5; i++) {
            UploadBean b = new UploadBean();
            b.imageID = i;
            cpBeans.add(b);
        }

        if (getIntent().getExtras() != null) {
            b = (CertificationInfoBean) getIntent().getExtras().getSerializable(Constants.KEY_CERINFO_BEAN);
            if (b != null) {
                txtProgress1.setBackgroundColor(getResources().getColor(R.color.transparent));
                txtProgress2.setBackgroundColor(getResources().getColor(R.color.transparent));
                txtProgress3.setBackgroundColor(getResources().getColor(R.color.transparent));
                txtProgress4.setBackgroundColor(getResources().getColor(R.color.transparent));
                txtProgress5.setBackgroundColor(getResources().getColor(R.color.transparent));
                txtProgress1.setText("");
                txtProgress2.setText("");
                txtProgress3.setText("");
                txtProgress4.setText("");
                txtProgress5.setText("");
                Glide.with(this).load(b.getImsAuthenRecord().getSelfieImg()).into(imgPhoto1);
                Glide.with(this).load(b.getImsAuthenRecord().getSightImg()).into(imgPhoto2);
                Glide.with(this).load(b.getImsAuthenRecord().getFaceImg()).into(imgPhoto3);
                Glide.with(this).load(b.getImsAuthenRecord().getEntiretyImg()).into(imgPhoto4);
                Glide.with(this).load(b.getImsAuthenRecord().getSideImg()).into(imgPhoto5);
                if(b.getImsAuthenRecord().getSelfieImg().equals(b.getImsAuthenRecord().getSpecifyPhoto())){
                    toPhotoPositon = 0;
                }else if(b.getImsAuthenRecord().getSideImg().equals(b.getImsAuthenRecord().getSpecifyPhoto())){
                    toPhotoPositon = 1;
                }else if(b.getImsAuthenRecord().getFaceImg().equals(b.getImsAuthenRecord().getSpecifyPhoto())){
                    toPhotoPositon = 2;
                }else if(b.getImsAuthenRecord().getEntiretyImg().equals(b.getImsAuthenRecord().getSpecifyPhoto())){
                    toPhotoPositon = 3;
                }else if(b.getImsAuthenRecord().getSideImg().equals(b.getImsAuthenRecord().getSpecifyPhoto())){
                    toPhotoPositon = 4;
                }
                toshow();
                if(b.getPhotosAuthenStatus() ==2){
                    btnUplade.setText("审核中");
                    btnUplade.setEnabled(false);
                }else if(b.getPhotosAuthenStatus() ==3){
                    btnUplade.setText("重新提交");
                    txt_fail_msg.setVisibility(View.VISIBLE);
                    txt_fail_msg.setText("驳回原因："+b.getImsAuthenRecord().getRemark()+"\n点击更换照片重新认证");
                    cpBeans.get(0).setLocalPath(b.getImsAuthenRecord().getSelfieImg());
                    cpBeans.get(1).setLocalPath(b.getImsAuthenRecord().getSightImg());
                    cpBeans.get(2).setLocalPath(b.getImsAuthenRecord().getFaceImg());
                    cpBeans.get(3).setLocalPath(b.getImsAuthenRecord().getEntiretyImg());
                    cpBeans.get(4).setLocalPath(b.getImsAuthenRecord().getSideImg());
                }else if(b.getPhotosAuthenStatus() ==1){
                    btnUplade.setText("认证通过");
                    btnUplade.setEnabled(false);
                    cpBeans.get(0).setLocalPath(b.getImsAuthenRecord().getSelfieImg());
                    cpBeans.get(1).setLocalPath(b.getImsAuthenRecord().getSightImg());
                    cpBeans.get(2).setLocalPath(b.getImsAuthenRecord().getFaceImg());
                    cpBeans.get(3).setLocalPath(b.getImsAuthenRecord().getEntiretyImg());
                    cpBeans.get(4).setLocalPath(b.getImsAuthenRecord().getSideImg());
                }
            }
        }
        if(b==null){
            getShowBgImg();
        }

    }

    /**
     * 在没有进行认证时，使用后台提供的默认背景图
     */
    private void getShowBgImg() {
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    ArrayList<PhotoBgInfo> tem = (ArrayList<PhotoBgInfo>) result.getData();
                    if(tem!=null&&tem.size()>=5){
                        if(!UIUtils.isEmpty(tem.get(0).getValue()))
                        Glide.with(ActivityCertificationPhoto.this).load(tem.get(0).getValue()).into(imgPhoto1);
                        if(!UIUtils.isEmpty(tem.get(1).getValue()))
                        Glide.with(ActivityCertificationPhoto.this).load(tem.get(1).getValue()).into(imgPhoto2);
                        if(!UIUtils.isEmpty(tem.get(2).getValue()))
                        Glide.with(ActivityCertificationPhoto.this).load(tem.get(2).getValue()).into(imgPhoto3);
                        if(!UIUtils.isEmpty(tem.get(3).getValue()))
                        Glide.with(ActivityCertificationPhoto.this).load(tem.get(3).getValue()).into(imgPhoto4);
                        if(!UIUtils.isEmpty(tem.get(4).getValue()))
                        Glide.with(ActivityCertificationPhoto.this).load(tem.get(4).getValue()).into(imgPhoto5);
                    }
                } else {
                    ToastUtil.getInstance().showToast(ActivityCertificationPhoto.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityCertificationPhoto.this, error);
            }

        }, PhotoBgInfo.class, HttpDataRequest.TYPE_LIST).POST(HttpDataReqUrl.URL_POST_GET_CERTIFICATION_PIC_BG, true, map);
    }

    @Override
    public void onReceiver(Context context, Intent intent) {

    }

    @OnClick({R.id.txt_progress1, R.id.txt_photo1, R.id.txt_progress2, R.id.txt_photo2, R.id.txt_progress3, R.id.txt_photo3, R.id.txt_progress4, R.id.txt_photo4, R.id.txt_progress5, R.id.txt_photo5, R.id.btn_uplade})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.txt_progress1:
                toPhotoPositon = 0;
                toCamera();
                break;
            case R.id.txt_progress2:
                toPhotoPositon = 1;
                toCamera();
                break;
            case R.id.txt_progress3:
                toPhotoPositon = 2;
                toCamera();
                break;
            case R.id.txt_progress4:
                toPhotoPositon = 3;
                toCamera();
                break;
            case R.id.txt_progress5:
                toPhotoPositon = 4;
                toCamera();
                break;
            case R.id.txt_photo1:
                if(b!=null){
                    toSetShow(0);
                    return;
                }
                toShowPositon = 0;
                toshow();
                break;
            case R.id.txt_photo2:
                if(b!=null){
                    toSetShow(1);
                    return;
                }
                toShowPositon = 1;
                toshow();
                break;
            case R.id.txt_photo3:
                if(b!=null){
                    toSetShow(2);
                    return;
                }
                toShowPositon = 2;
                toshow();
                break;
            case R.id.txt_photo4:
                if(b!=null){
                    toSetShow(3);
                    return;
                }
                toShowPositon = 3;
                toshow();
                break;
            case R.id.txt_photo5:
                if(b!=null){
                    toSetShow(4);
                    return;
                }
                toShowPositon = 4;
                toshow();
                break;
            case R.id.btn_uplade:
                if (checkedPhotos()) {
                    showLoadingDialog(false);
                    if (failuplist.size() > 0) {
                        toUploadPhoto(failuplist);
                        return;
                    }
                    toUploadPhoto(cpBeans);
                }
                break;
        }
    }

    /**
     * 设置认证照片的展示照
     * @param position
     */
    private void toSetShow(final int position) {
        if(b.getPhotosAuthenStatus()!=1){
            return;
        }
        showLoadingDialog();
        MyHashMap map = new MyHashMap();
        map.put("number",(position+1)+"");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    toShowPositon = position;
                    toshow();
                } else {
                    ToastUtil.getInstance().showToast(ActivityCertificationPhoto.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityCertificationPhoto.this, error);
            }

        }, null, null).POST(HttpDataReqUrl.URL_POST_SET_SHOW_PIC, true, map);

    }

    private void toshow() {
        Drawable drawable = getResources().getDrawable(R.drawable.certification_photo_show2);
        Drawable drawable2 = getResources().getDrawable(R.drawable.certification_photo_show);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        drawable2.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        txtPhoto1.setCompoundDrawables(drawable, null, null, null);
        txtPhoto2.setCompoundDrawables(drawable, null, null, null);
        txtPhoto3.setCompoundDrawables(drawable, null, null, null);
        txtPhoto4.setCompoundDrawables(drawable, null, null, null);
        txtPhoto5.setCompoundDrawables(drawable, null, null, null);
        switch (toShowPositon) {
            case 0:
                txtPhoto1.setCompoundDrawables(drawable2, null, null, null);
                break;
            case 1:
                txtPhoto2.setCompoundDrawables(drawable2, null, null, null);
                break;
            case 2:
                txtPhoto3.setCompoundDrawables(drawable2, null, null, null);
                break;
            case 3:
                txtPhoto4.setCompoundDrawables(drawable2, null, null, null);
                break;
            case 4:
                txtPhoto5.setCompoundDrawables(drawable2, null, null, null);
                break;
        }
    }

    /**
     * 检查是否照片设置完成
     *
     * @return
     */
    private boolean checkedPhotos() {
        if(b!=null&&b.getPhotosAuthenStatus()==3){
            boolean isHttp = false;
            for (int i = 0; i < cpBeans.size(); i++) {
                if (!cpBeans.get(i).localPath.contains("http")) {
                    isHttp = true;
                }
            }
            if(!isHttp){
                ToastUtil.getInstance().showToast(ActivityCertificationPhoto.this,"您未修改任何图片");
                return false;
            }
        }
        for (int i = 0; i < cpBeans.size(); i++) {
            if (TextUtils.isEmpty(cpBeans.get(i).localPath)) {
                ToastUtil.getInstance().showToast(ActivityCertificationPhoto.this,"请先设置图片");
                return false;
            }
        }
        return true;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        dissmissLoadingDialog();
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_CAPTURE:
                    ImageUtils.cropImage(ActivityCertificationPhoto.this);
                    break;
                case REQUEST_CODE_CROP_ICON:
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), ImageUtils.TEMP_PHOTO_FILE_NAME);
                    if (file.exists()) {// 如果图片存在
                        Message message = new Message();
                        message.what = 1;
                        message.obj = file.getAbsolutePath();
                        mHandler.sendMessage(message);
                    }
                    break;
                case REQUEST_CODE_CALLERY:
                    if (data == null) {
                        return;
                    }
                    ImageUtils.galleryResultCropImage(ActivityCertificationPhoto.this, data.getData(), ActivityCertificationPhoto.this);
                    break;
            }
        }
    }

    /**
     * 调起照相机进行拍照或者相册选择图片
     */
    private void toCamera() {
        if(b!=null&&(b.getPhotosAuthenStatus()==2||b.getPhotosAuthenStatus()==1)){
            Intent intent = new Intent(ActivityCertificationPhoto.this, PhotoPreviewActivity.class);
            ArrayList<PhotoInfo> list = new ArrayList<PhotoInfo>();
            PhotoInfo p = new PhotoInfo();
            String path = "";
            switch (toPhotoPositon){
                case 0:
                    path =b.getImsAuthenRecord().getSelfieImg();
                    break;
                case 1:
                    path =b.getImsAuthenRecord().getSightImg();
                    break;
                case 2:
                    path =b.getImsAuthenRecord().getFaceImg();
                    break;
                case 3:
                    path =b.getImsAuthenRecord().getEntiretyImg();
                    break;
                case 4:
                    path =b.getImsAuthenRecord().getSideImg();
                    break;
            }
            p.setPhotoPath(path);
            Bitmap bitmap = ImageLoader.load(ActivityCertificationPhoto.this, p.getPhotoPath());
            if (bitmap != null) {
                p.setWidth(bitmap.getWidth());
                p.setHeight(bitmap.getHeight());
            }
            list.add(p);
            intent.putExtra(PhotoPreviewActivity.PHOTO_LIST, list);
            startActivity(intent);
            return;
        }
        BottomUpDialog bottomUpDlg = new BottomUpDialog(ActivityCertificationPhoto.this, new String[]{"拍照", "从相册中选择"}, new BottomUpDialog.OnPositionClickListener2() {
            @Override
            public void onPositionClick(int position, BottomUpDialog dialog) {
                switch (position) {
                    case 0:
                        ActivityCertificationPhotoPermissionsDispatcher.getCameraPermissionWithCheck(ActivityCertificationPhoto.this);
                        break;
                    case 1:
                        ImageUtils.openGalleryForResult(ActivityCertificationPhoto.this, ActivityCertificationPhoto.REQUEST_CODE_CALLERY);
                        break;
                }
                dialog.dismiss();
            }
        });
        bottomUpDlg.show();
    }

    /**
     * 上传照片并进行认证
     *
     * @param uploads
     */
    private void toUploadPhoto(ArrayList<UploadBean> uploads) {
        ArrayList<UploadBean> tem = new ArrayList<>();
        for (int i = 0; i < uploads.size(); i++) {
            tem.add(uploads.get(i).copy());
        }
        new ImagesBulkUpload(ActivityCertificationPhoto.this, tem, false, new ImagesBulkUpload.OnBulkImagesUploadListener() {

            @Override
            public void onImageUploadProgress(UploadBean image, long progress, long total) {
                if (total > 0) {
                    if (image.imageID == 0) {
                        txtProgress1.setText(progress * 100 / total + "%");
                    } else if (image.imageID == 1) {
                        txtProgress2.setText(progress * 100 / total + "%");
                    } else if (image.imageID == 2) {
                        txtProgress3.setText(progress * 100 / total + "%");
                    } else if (image.imageID == 3) {
                        txtProgress4.setText(progress * 100 / total + "%");
                    } else if (image.imageID == 4) {
                        txtProgress5.setText(progress * 100 / total + "%");
                    }
                }
            }

            @Override
            public void onImageUploadSucceed(UploadBean image) {
                image.isSuccess = true;
                if (image.imageID == 0) {
                    txtProgress1.setText("");
                } else if (image.imageID == 1) {
                    txtProgress2.setText("");
                } else if (image.imageID == 2) {
                    txtProgress3.setText("");
                } else if (image.imageID == 3) {
                    txtProgress4.setText("");
                } else if (image.imageID == 4) {
                    txtProgress5.setText("");
                }
            }

            @Override
            public void onImageUploadFailed(UploadBean image) {
                if (image.imageID == 0) {
                    txtProgress1.setText("上传失败");
                } else if (image.imageID == 1) {
                    txtProgress2.setText("上传失败");
                } else if (image.imageID == 2) {
                    txtProgress3.setText("上传失败");
                } else if (image.imageID == 3) {
                    txtProgress4.setText("上传失败");
                } else if (image.imageID == 4) {
                    txtProgress5.setText("上传失败");
                }
            }

            @Override
            public void onFinished(List<UploadBean> imagesUploadFailed) {
                if (imagesUploadFailed.size() == 0) {
                    toCertification();
                    btnUplade.setText("上传成功");
                } else {
                    failuplist.addAll(imagesUploadFailed);
                    btnUplade.setText("点击重试");
                    dissmissLoadingDialog();
                }
            }
        }).upload(0.7f);
    }
    String[] complaintImageStr = new String[5];
    /**
     * 上传完成之后提交服务器操作
     *
     */
    private void toCertification() {
        showLoadingDialog();
        for (int i = 0; i < ActivityCertificationPhoto.this.cpBeans.size(); i++) {
            complaintImageStr[i] = (TextUtils.isEmpty(ActivityCertificationPhoto.this.cpBeans.get(i).cloudKey)?ActivityCertificationPhoto.this.cpBeans.get(i).localPath:ActivityCertificationPhoto.this.cpBeans.get(i).cloudKey);
        }
        MyHashMap map = new MyHashMap();
        map.put("imgs", complaintImageStr[0]+","+complaintImageStr[1]+","+complaintImageStr[2]+","+complaintImageStr[3]+","+complaintImageStr[4]);
        map.put("designated", (toShowPositon+1)+"");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog();
                if (result.getCode() == 0) {
                    ToastUtil.getInstance().showToast(ActivityCertificationPhoto.this, "认证提交成功");
                    finish();
                } else {
                    ToastUtil.getInstance().showToast(ActivityCertificationPhoto.this, result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog();
                ToastUtil.getInstance().showToast(ActivityCertificationPhoto.this, error);
            }

        }, null, null).POST(HttpDataReqUrl.URL_GET_CERTIFICATION_PHOTO, true, map);
    }


    @NeedsPermission(Manifest.permission.CAMERA)
    public void getCameraPermission() {
        ImageUtils.captureForResult(ActivityCertificationPhoto.this, REQUEST_CODE_CAPTURE);
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    public void showRationaleForCamera(final PermissionRequest request) {
        request.proceed();
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    public void deniedCameraPermission() {
        ToastUtil.getInstance().showDialog(ActivityCertificationPhoto.this, getString(R.string.denied_camera_permission));
    }

    @Override
    public void onSelectDone() {
        File tempFile1 = ImageUtils.getCropFile();
        if (null == tempFile1 || !tempFile1.exists() || tempFile1.length() == 0) {
            tempFile1 = new File(FileUtils.getTempCacheDir(), ImageUtils.TEMP_PHOTO_FILE_NAME);
            if (null == tempFile1 || !tempFile1.exists() || tempFile1.length() == 0) {
                ToastUtil.getInstance().showToast(this, "上传图片失败, 请重试!");
                return;
            }
        }
        final File tempFile = tempFile1;
        new Thread() {
            @Override
            public void run() {
                String tempPath = BitmapHelper.compressBitmap(tempFile.getPath(), DisplayUtil.dip2px(ActivityCertificationPhoto.this, 300), DisplayUtil.dip2px(ActivityCertificationPhoto.this, 200));
//                String tempPath = tempFile.getPath();
                if (!TextUtils.isEmpty(tempPath) && new File(tempPath).exists()) {
                    Message message = new Message();
                    message.what = 1;
                    message.obj = tempPath;
                    mHandler.sendMessage(message);
                    return;
                }
                ToastUtil.getInstance().showToast(ActivityCertificationPhoto.this, R.string.image_parse_fail);
            }
        }.start();
    }

    @Override
    public void onSelectFail() {
        ToastUtil.getInstance().showToast(this, R.string.image_format_fail);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (cpBeans.get(toPhotoPositon) != null) {
                cpBeans.get(toPhotoPositon).localPath = (String) msg.obj;
                Glide.with(ActivityCertificationPhoto.this)
                        .load(Uri.fromFile(new File((String) msg.obj)))
                        .bitmapTransform(new RoundedCornersTransformation(ActivityCertificationPhoto.this, 4, 0, RoundedCornersTransformation.CornerType.ALL))
                        .into(imageViews.get(toPhotoPositon));
                cpBeans.get(toPhotoPositon).bucketName = UserInfoUtils.getCachedLoginUser().getACCOUNTCONFIG().getBucketone();
                cpBeans.get(toPhotoPositon).cloudKey = UserInfoUtils.getCachedLoginUser().getUSER().getDmId() + "/" + StringUtil.getUniqueString() + Constants.IMAGE_FILE_SUFFIX;
                if(b!=null){
                    failuplist.add(cpBeans.get(toPhotoPositon));
                }
                switch (toPhotoPositon){
                    case 0:
                        txtProgress1.setText("");
                        txtProgress1.setBackgroundColor(getResources().getColor(R.color.transparent));
                        break;
                    case 1:
                        txtProgress2.setText("");
                        txtProgress2.setBackgroundColor(getResources().getColor(R.color.transparent));
                        break;
                    case 2:
                        txtProgress3.setText("");
                        txtProgress3.setBackgroundColor(getResources().getColor(R.color.transparent));
                        break;
                    case 3:
                        txtProgress4.setText("");
                        txtProgress4.setBackgroundColor(getResources().getColor(R.color.transparent));
                        break;
                    case 4:
                        txtProgress5.setText("");
                        txtProgress5.setBackgroundColor(getResources().getColor(R.color.transparent));
                        break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
